<?php
namespace app\shops\controller;

use think\Controller;
use think\Db;
use think\Session;

use think\captcha\Captcha;

class Login extends Controller
{
	/**
     * @throws
	 * 登陆首页
	 * @return [type] [description]
	 */
    public function index()
    {   
        // 异步登陆处理
		if(request()->isAjax()){

            // 接收数据
            $shop_no    = request()->post('shop_no');
            $username   = request()->post('username');
            $passwd     = request()->post('passwd');
            $verify     = request()->post('verify');

            // 验证码类
            $captcha    = new Captcha();

            // 验证验证码
            $result     = $captcha->check($verify);
            if($result===false){
                $this->error('验证码错误');
            }

            // 用户名密码非空
            if(!$shop_no || !$username || !$passwd){
                $this->error('账号信息不可为空');
            }

            // 查询商户信息
            $shop_info = Db("shops")->where('shop_no',$shop_no)->where('user_name',$username)->find();
            if(!$shop_info){
                $this->error('用户不存在');
            }

            // 是否关闭
            if($shop_info['status'] == 0){
                $this->error("审核中，请联系管理员");
            }elseif($shop_info['status'] == -1){
                $this->error("店铺已关闭");
            }elseif($shop_info['status'] != 1){
                $this->error("非法访问");
            }

            // 验证密码是否都一致
            if($shop_info['password'] != md5(trim($passwd))){
                $this->error('密码错误');
            }

            // 更新用户信息
            $params['shop_id']      = $shop_info['shop_id'];
            $params['login_time']   = time();
            $params['login_num']    = $shop_info['login_num'] + 1;
            $params['login_ip']     = request()->ip();
            Db('shops')->update($params);

            // 写入缓存
            Session::set('shop_id',$shop_info['shop_id']);
            Session::set('shop_user_name',$shop_info['user_name']);
            Session::set('shop_name',$shop_info['shop_name']);

            $this->success('登陆成功');
        }

		return $this->fetch();
	}


	/**
     * 生成验证码
     *
     * 参考：http://blog.csdn.net/leejianjun/article/details/78720698
     */
    public function verify()
    {
        $captcha = new Captcha();  

        $captcha->imageW    = 121;              // 图片宽
        $captcha->imageH    = 35;               // 图片高  
        $captcha->fontSize  = 14;               // 字体大小  
        $captcha->length    = 4;                // 字符数  
        $captcha->fontttf   = '5.ttf';          // 字体  
        $captcha->expire    = 30;               // 有效期  
        $captcha->useCurve  = false;            // 是否加混淆曲线
        $captcha->useNoise  = true;             // 不添加杂点  

        return $captcha->entry();  
    }


    /**
     * 退出 / 切换账户
     */
    public function logOut()
    {   
        // 清除缓存
        Session(null);

        // 跳转登录页 
        $this->redirect('login/index');
    }
}
